'use server'

import prisma from "@/lib/prisma"
import { App, ChatMessage, ChatSession } from "@prisma/client"

export const upsertApp = async (data: Omit<App, 'createdAt' | 'updatedAt'>) => {
    const { id, name, type, description } = data
    const result = await prisma.app.upsert({
        where: { id },
        update: { name, type, description },
        create: { name, type, description }
    })

    return result
}

export const upsertChatSession = async (data: Omit<ChatSession, 'createdAt' | 'updatedAt'>) => {
    const { id, appId, topic, temperature, topPolarity, maxTokens } = data
    const result = await prisma.chatSession.upsert({
        where: { id, appId },
        update: { topic, temperature, topPolarity, maxTokens },
        create: { appId, topic, temperature, topPolarity, maxTokens }
    })

    return result
}

export const upsertChatMessage = async (data: Omit<ChatMessage, 'createdAt' | 'updatedAt'>) => {
    const { id, content, responseTime, requestTokens, responseTokens, order, messageId, sessionId } = data
    const result = await prisma.chatMessage.upsert({
        where: { id, sessionId },
        update: { content, responseTime, requestTokens, responseTokens, order, messageId },
        create: { sessionId, content, responseTime, requestTokens, responseTokens, order, messageId },
    })

    return result
}